home *** CD-ROM | disk | FTP | other *** search
/ Language/OS - Multiplatform Resource Library / LANGUAGE OS.iso / a_utils / _archvrs / unix / arc521.lha / arc / minix / scandir.c < prev    next >
C/C++ Source or Header  |  1989-08-08  |  2KB  |  86 lines

  1. /*
  2. **  SCANDIR
  3. **  Scan a directory, collecting all (selected) items into a an array.
  4. */
  5. #include <stdio.h>
  6. #include <sys/types.h>
  7. #include <dirent.h>
  8.  
  9. #ifdef    RCSID
  10. static char RCS[] = "$Header: scandir.c,v 1.1 87/12/29 21:35:56 rsalz Exp $";
  11. #endif    /* RCSID */
  12.  
  13. /* Initial guess at directory size. */
  14. #define INITIAL_SIZE    20
  15.  
  16. /* A convenient shorthand. */
  17. typedef struct dirent     ENTRY;
  18.  
  19. /* Linked in later. */
  20. extern char        *malloc();
  21. extern char        *realloc();
  22. extern char        *strcpy();
  23.  
  24.  
  25. int
  26. scandir(Name, List, Selector, Sorter)
  27.     char          *Name;
  28.     ENTRY        ***List;
  29.     int             (*Selector)();
  30.     int             (*Sorter)();
  31. {
  32.     register ENTRY     **names;
  33.     register ENTRY      *E;
  34.     register DIR      *Dp;
  35.     register int       i;
  36.     register int       size;
  37.  
  38.     /* Get initial list space and open directory. */
  39.     size = INITIAL_SIZE;
  40.     if ((names = (ENTRY **)malloc(size * sizeof names[0])) == NULL
  41.      || (Dp = opendir(Name)) == NULL)
  42.     return(-1);
  43.  
  44.     /* Read entries in the directory. */
  45.     for (i = 0; E = readdir(Dp); )
  46.     if (Selector == NULL || (*Selector)(E)) {
  47.         /* User wants them all, or he wants this one. */
  48.         if (++i >= size) {
  49.         size <<= 1;
  50.         names = (ENTRY **)realloc((char *)names, size * sizeof names[0]);
  51.         if (names == NULL) {
  52.             closedir(Dp);
  53.             return(-1);
  54.         }
  55.         }
  56.  
  57.         /* Copy the entry. */
  58. #ifdef atarist
  59.         if ((names[i - 1] = (ENTRY *)malloc(DIRSIZ)) == NULL) { 
  60. #else
  61.         if ((names[i - 1] = (ENTRY *)malloc(E->d_reclen)) == NULL) { 
  62. #endif
  63.         closedir(Dp);
  64.         return(-1);
  65.         }
  66.         names[i - 1]->d_ino = E->d_ino;
  67. #ifndef atarist
  68.         names[i - 1]->d_off = E->d_off;
  69.         names[i - 1]->d_reclen = E->d_reclen;
  70. #endif
  71.      /*   names[i - 1]->d_namlen = E->d_namlen; */
  72.         (void)strcpy(names[i - 1]->d_name, E->d_name);
  73.     }
  74.  
  75.     /* Close things off. */
  76.     names[i] = NULL;
  77.     *List = names;
  78.     closedir(Dp);
  79.  
  80.     /* Sort? */
  81.     if (i && Sorter)
  82.     qsort((char *)names, i, sizeof names[0], Sorter);
  83.  
  84.     return(i);
  85. }
  86.